﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows;
using System.Windows.Media;
using System.Data;
using System.Collections;
using CMD_DKT.ClientsDGrid;
using CMD_DKT.BAL;

namespace CMD_DKT
{

    public static class ClientsGrid
    {

        /// <summary>
        /// Crea dinámicamente un DataGrid en base a las columnas del DataTable fuente y las características de una Lista de características
        /// </summary>
        /// <param name="name">Nombre del Grid</param>
        /// <param name="dt">DataTable con datos y estructura fuente</param>
        /// <param name="feat">Lista de características de las columnas del Grid</param>
        /// <returns></returns>
        public static DataGrid createClientsGrid(string name, DataTable dt, List<Features> feat, string dictionaryPath)
        {
            DataGrid ClientGrid = new DataGrid();
            ClientGrid.Name = name;

            #region COLUMNS

            try
            {
                BindData(ClientGrid, dt, feat);                
            }
            catch (Exception ex)
            {
                MessageBox.Show("createGrid: " + ex.Message);
            }

            #endregion

            #region Look & Feel
            ClientGrid.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            ClientGrid.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;

            

            ClientGrid.CanUserAddRows = false;
            ClientGrid.CanUserDeleteRows = false;

            ClientGrid.CanUserResizeColumns = true;
            ClientGrid.CanUserResizeRows = true;
            ClientGrid.AutoGenerateColumns = false;
            //ClientGrid.MouseDoubleClick += new System.Windows.Input.MouseButtonEventHandler(ClientGrid_MouseDoubleClick);
            
            ClientGrid.IsReadOnly = false;
            ClientGrid.SelectionMode = DataGridSelectionMode.Single;
            ClientGrid.ColumnWidth = new DataGridLength(1,DataGridLengthUnitType.Star);//DataGridLength.Auto;

            // -------      Grid Style
            ResourceDictionary rd = SetDictionaryStyle(dictionaryPath);
            if (rd.Count > 0)
            {
                //Header
                Style stHeader = rd["HeaderStyle"] as Style;
                ClientGrid.ColumnHeaderStyle = stHeader;

                //Rows
                ClientGrid.RowStyle = rd["RowStyle"] as Style;

                //Grid
                Style stGrid = rd["GridStyle"] as Style;
                ClientGrid.Style = stGrid;
            }
            #endregion

            return ClientGrid;
        }

        /// <summary>
        /// Devuelve un Diccionario de recursos creado en base al path que recibe como parámetro
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static ResourceDictionary SetDictionaryStyle(string path )
        {
            ResourceDictionary rd = new ResourceDictionary();
            try
            {
                rd.Source = new Uri(path, UriKind.RelativeOrAbsolute);
            }catch(Exception ex){
            
            }
            return rd;
        }


        /// <summary>
        /// Elimina los renglones del grid que estén seleccionados en la columna de ckeckBox
        /// </summary>
        /// <param name="dg"></param>
        public static void DeleteRows(DataGrid dg)
        {
            

            int cnt = 0;
            string ids = "";
            ArrayList isChecked = new ArrayList();

            if (dg != null)
            {
                try
                {
                    for (int i = 0; i < dg.Items.Count; i++)
                    {
                        DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(i);
                        CheckBox cellContent = dg.Columns[0].GetCellContent(row) as CheckBox;

                        if (cellContent != null && cellContent.IsChecked == true)
                        {
                            object item = dg.Items[i];
                            DataRowView drv = (DataRowView)item;

                            isChecked.Add(i);
                            if (drv[0].ToString() != "")
                            {
                                // Se guardan los Ids de los registros a eliminar en la BD
                                if (ids == "")
                                    ids = drv[0].ToString();
                                else ids = ids + "," + drv[0].ToString();
                            }
                            //drv.Delete();
                            cnt++;
                        }//if

                    }//for


                    if (cnt == 0)
                    {
                        MessageBox.Show("No hay elementos seleccionados en el Grid.");
                        return;
                    }

                    if (ids != "")
                    {
                        //Elimina registros de la Base de Datos
                        Solicitud.DeleteData(ids);

                        //Elimina registros del Grid
                        isChecked.Sort();
                        isChecked.Reverse();

                        foreach (var row in isChecked)
                        {
                            int i = int.Parse(row.ToString());
                            
                                object item = dg.Items[i];


                                //dg.Items.RemoveAt(i);
                                DataRowView drv = (DataRowView)item;
                                if (drv[0].ToString() != "")
                                {
                                    drv.EndEdit();
                                    drv.Delete();
                                }
                            
                        }//foreach
                        dg.CommitEdit(DataGridEditingUnit.Row, true);
                        dg.CancelEdit();
                        dg.Items.Refresh();
                    }//if

                    
                }catch(Exception ex)
                {
                    throw new Exception(ex.Message);
                    //MessageBox.Show(ex.Message);
                    //dg.CancelEdit();
                    //dg.Items.Refresh();
                }

            }
        }// end DeleteRows
        public static void EliminarRegistros(Grid dg)
        {
            Boolean Bandera=false;
            Boolean NoEsBorrador=false;
            MessageBoxResult respuesta=MessageBoxResult.Cancel;
            if (dg != null)
            {
                try
                {
                    foreach (var child in dg.Children)
                    {
                        //if (child.GetType() == typeof(System.Windows.Controls.DataGrid))
                        if (child.GetType() == typeof(System.Windows.Controls.CheckBox))
                        {
                            CheckBox chk = (CheckBox)child;

                            if (chk.IsChecked == true)
                            {
                                if(!Bandera)
                                    respuesta = MessageBox.Show("¿Desea continuar con la eliminación?", "Eliminación de Solicitudes", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                                Bandera=true;
                            }
                            if (respuesta == MessageBoxResult.Yes && chk.IsChecked==true)
                            {
                                string Element = chk.Name.ToString();
                                
                                int cero = chk.Name.ToString().Length - 2;
                                Element = Element.Substring(2, cero);
                                if (Solicitud.GetStatus(Element).Rows[0]["ID_SOLICITUD_STATUS"].ToString() == "1")
                                    Solicitud.DeleteData(Element);
                                else
                                    NoEsBorrador = true;

                            }
                        }
                        //else
                        //    if(child.GetType() == typeof(System.Windows.Controls.TextBlock))
                        //    {
                        //        ((TextBlock)child).Text
                        //    }
                    }//foreach
                    if (!Bandera)
                        MessageBox.Show("Seleccione al menos una solicitud", "Atención", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    else
                        if(NoEsBorrador)
                            MessageBox.Show("Solo es posible eliminar las soluciones de status borrador", "Atención", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                    //MessageBox.Show(ex.Message);
                    //dg.CancelEdit();
                    //dg.Items.Refresh();
                }
            }           
        }// end DeleteRows

        /// <summary>
        /// Realiza un Rebind sobre un DataGrid
        /// </summary>
        /// <param name="dg">DataGrid objetivo</param>
        /// <param name="dt">DataTable fuente</param>
        public static void BindData(DataGrid dg, DataTable dt, List<Features> feat)
        {
            dg.Columns.Clear();

            // Add checkbox column
            DataGridCheckBoxColumn check = new DataGridCheckBoxColumn();
            check.IsReadOnly = false;
            check.Width = new DataGridLength(1, DataGridLengthUnitType.SizeToCells);

            dg.Columns.Add(check);

            try
            {
                // Creates columns based on Features List definition
                foreach (Features item in feat)
                {
                    string nombre = item.Name;

                    DataGridTextColumn col = new DataGridTextColumn();
                    col.Binding = new Binding(nombre);
                    col.Header = nombre;
                    col.IsReadOnly = true;
                    col.Width = new DataGridLength(1, DataGridLengthUnitType.Star);//DataGridLength.Auto;

                    if (!item.Visible)
                        col.Visibility = Visibility.Hidden;

                    if (item.Image)
                    {
                        //------------ Create Image Type columns
                        DataGridTemplateColumn imgStatus = new DataGridTemplateColumn();
                        imgStatus.Header = item.Name;
                        imgStatus.Width = new DataGridLength(1, DataGridLengthUnitType.SizeToCells);

                        FrameworkElementFactory factory1 = new FrameworkElementFactory(typeof(Image));
                        Binding b1 = new Binding(dt.Columns[item.Name].ToString());
                        b1.Mode = BindingMode.TwoWay;
                        factory1.SetValue(Image.SourceProperty, b1);
                        DataTemplate cellTemplate1 = new DataTemplate();
                        cellTemplate1.VisualTree = factory1;

                        imgStatus.CanUserResize = true;
                        imgStatus.CellTemplate = cellTemplate1;
                        dg.Columns.Add(imgStatus);
                        //---------

                    }
                    else
                        dg.Columns.Add(col);

                  
                   
                }
            }catch(Exception ex){
                throw new Exception(ex.Message);
            }

            // DataGrid binds
            dg.ItemsSource = dt.DefaultView;
           

            
        }//end BindData

        /// <summary>
        /// Event Handler del doble click sobre un renglón del grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void ClientGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {           
            DataGrid grid = (DataGrid)sender;
            DataRowView dr = (DataRowView)grid.SelectedItem;
            try
            {
                string Id = dr[0].ToString();
                CheckBox check = grid.Columns[0].GetCellContent(dr) as CheckBox;// DataGridCheckBoxColumn;


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }//end ClientGrid_MouseDoubleClick


        /// <summary>
        /// Agrega un DataGrid a un StackPanel
        /// </summary>
        /// <param name="panel">StackPanel destino</param>
        /// <param name="grid">Grid a agregar</param>
        public static void AddClientsGrid(StackPanel panel, DataGrid grid)
        {
            panel.Children.Add(grid);

        }

      
        

    }// end class
}
